package com.itheima.controller;

import cn.hutool.core.bean.BeanUtil;
import com.itheima.common.R;
import com.itheima.constant.TokenConstant;
import com.itheima.dto.AddCartDTO;
import com.itheima.dto.DeleteCartDTO;
import com.itheima.pojo.ShoppingCart;
import com.itheima.service.ShoppingCartService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Author 小帅蓝
 * @Date 2022/6/22 14:09
 */
@RestController
@RequestMapping("/shoppingCart")
public class ShoppingCartController {

    @Resource
    private ShoppingCartService shoppingCartService;
    @Resource
    private RedisTemplate<Object, Object> redisTemplate;

    @PostMapping("/add")
    public R<ShoppingCart> addShopCart(@RequestBody AddCartDTO addCartDTO) {

        Boolean lock = redisTemplate.opsForValue().setIfAbsent(TokenConstant.USER_TOKEN_PREFIX + "_lock", "lock", 1, TimeUnit.SECONDS);
        if (!lock) {
            return R.error("请勿频繁点击");
        }
        ShoppingCart shoppingCart = new ShoppingCart();
        BeanUtil.copyProperties(addCartDTO, shoppingCart);
        ShoppingCart cart = shoppingCartService.addShoppingCart(shoppingCart);
        return R.success(cart);
    }

    @GetMapping("/list")
    public R<List<ShoppingCart>> queryAll() {
        List<ShoppingCart> list = shoppingCartService.queryAll();
        return R.success(list);
    }

    @DeleteMapping("/clean")
    public R<String> deleteAll() {
        return shoppingCartService.deleteAll();
    }

    @PostMapping("/sub")
    public R<String> deleteShoppingCart(@RequestBody DeleteCartDTO deleteCartDTO) {
        String dishId = deleteCartDTO.getDishId();
        String setmealId = deleteCartDTO.getSetmealId();
        return shoppingCartService.deleteShoppingCart(dishId, setmealId);
    }

}
